//
//  OAuthViewController.swift
//  01sinablog
//
//  Created by ZhangZiang on 15/12/13.
//  Copyright © 2015年 ZhangZiang. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController, UIWebViewDelegate {

    let webView = UIWebView()
    
    override func loadView() {
        view = webView
        
        webView.delegate = self
         }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadOAuthURL()
        setupNavigation()
    }
 
    //加载授权页面
    private func loadOAuthURL()
    {
        let urlString : String = "https://api.weibo.com/oauth2/authorize?" +
        "client_id=" + client_id + "&redirect_uri=" + redirect_uri
//        print(urlString)
        let url = NSURL(string: urlString)
        
        webView.loadRequest(NSURLRequest(URL: url!))
        
    }
    
    private func setupNavigation()
    {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "dismissOAuthView")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoAccount")
    }
    //要加@objc才能兼容OC的target-action机制,否则会报错...
    @objc private func dismissOAuthView()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充,用JS代码实现
    @objc private func autoAccount()
    {
        //JS代码,可以在Safari里到授权页面查看元素试试
        let JSString = "document.getElementById('userId').value='18766313908', document.getElementById('passwd').value='a65526687b'"
        webView.stringByEvaluatingJavaScriptFromString(JSString)
    }
}
//webView的代理
extension OAuthViewController {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
     
        //判断,如果url是nil就返回假
        guard let urlString = request.URL?.absoluteString else
        {
            return false
        }
        //如果是授权页面就返回真
        if urlString.hasPrefix("https://api.weibo.com/")
        {
            return true
        }
        //回调成功后是百度,所以如果不是就返回假,是就继续
        if !urlString.hasPrefix("http://www.baidu.com/")
        {
            return false
        }
        
//        let urlString = request.URL?.absoluteString
        //"http://www.baidu.com/?code=fed3f84464fed98aa7d58998201fba9b"
//        print(urlString)
        
        //利用query可以获得url中的参数部分(code=......)
        if let query = request.URL?.query
        {
            let codeStr = "code="
            let code = query.substringFromIndex(codeStr.endIndex)
            loadToken(code)
        }
        
        
        return true
    }
    //去获取令牌,因为HTTP的请求方式是POST,不能像GET那样用浏览器加载,所以用AFN
    private func loadToken(code : String)
    {
        UserAccountViewModel().loadToken(code) { (isSuccess) -> () in
            if isSuccess
            {
                SVProgressHUD.dismiss()
                
                self.dismissOAuthView()
                print("登录成功")
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewController, object: "Welcome")
            }
            else
            {
                print("登录失败")
            }
        }
            }
 }